package com.sherlocky.document.service;

import com.sherlocky.document.constant.DocumentConstants;
import com.sherlocky.document.entity.Document;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;

/**
 * 默认的文档缓存业务实现（基于 Caffeine cache）
 * <p>未配置Redis时，注入该Bean</p>
 * @author: zhangcx
 * @date: 2019/8/9 15:50
 */
@Slf4j
@Service
@ConditionalOnMissingBean(RedisDocumentCacheService.class)
public class DefaultDocumentCacheService implements DocumentCacheService {
    // 暂时默认过期时间1天，最大数量5w
    private Cache<String, Document> dc = Caffeine.newBuilder()
            .expireAfterWrite(DocumentConstants.CACHE_DURATION)
            .maximumSize(50_000)
            .build();

    @Override
    public boolean put(String documentKey, Document doc) {
        if (doc == null) {
            return false;
        }
        dc.put(documentKey, doc);
        return true;
    }

    @Override
    public Document get(String documentKey) {
        return dc.getIfPresent(documentKey);
    }

    @Override
    public void remove(String documentKey) {
        dc.invalidate(documentKey);
    }
}
